import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'
import { createPinia } from 'pinia'

const pinia = createPinia()
const store = useUserStore(pinia)

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginView.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/RegisterView.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/',
      name: 'index',
      component: () => import('@/views/IndexView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/datatrace',
      name: 'datatrace',
      component: () => import('@/views/DataTraceView.vue'),
      meta: { requiresAuth: true }
    }
  ]
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 直接检查 localStorage 中的登录状态
  const token = localStorage.getItem('token')
  const isLogin = localStorage.getItem('isLogin') === 'true'
  const isAuthenticated = !!token && isLogin

  console.log('路由守卫检查:', {
    to: to.path,
    from: from.path,
    requiresAuth: to.meta.requiresAuth,
    token: token ? '存在' : '不存在',
    isLogin,
    isAuthenticated
  })

  // 如果路由需要认证且未登录
  if (to.meta.requiresAuth && !isAuthenticated) {
    console.log('需要认证但未登录，重定向到登录页面')
    alert('请先登录')
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
    return // 确保在重定向后不会继续执行
  }

  // 如果是登录页面且已登录
  if (to.path === '/login' && isAuthenticated) {
    console.log('已登录用户尝试访问登录页面，重定向到首页')
    next({ path: '/' })
    return // 确保在重定向后不会继续执行
  }

  // 其他情况正常通过
  console.log('允许路由导航')
  next()
})

export default router
